/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 *
 * $Id: RechargerClient.cpp,v 1.9 2009-10-26 12:47:02 morsko Exp $
 *
 * \file
 * \brief Implementation for Recharger interface client library.
 * \author Mikko Elomaa <mikko.elomaa@tkk.fi>
 * \author Antti Maula <antti.maula@tkk.fi>
 */

#include "RechargerClient.hpp"
#include "RechargerData.hpp"

//*****************************************************************************
using namespace MaCI::Recharger;
//*****************************************************************************
//*****************************************************************************
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

CRechargerClient::CRechargerClient(gimi::GIMI *aGIMIPtr, 
                           const int aInterfaceMinor)
  : CSync(1,1), // Max One Mutex, Max one Condition
    CThread(1), // Max one Thread.
    CMaCI(aGIMIPtr, GIMI_PROTOCOL_MACI_RECHARGER, aInterfaceMinor),
    iRechargerDataSequence(0),
    iRechargerCommandSequence(0),
    iLastRechargerData(),
    iRechargerClientCallback(NULL)
{
  dPrint(4,"CRechargerClient %p constructed", this);
}
//*****************************************************************************

CRechargerClient::~CRechargerClient()
{
  DoClose();
  dPrint(4,"CRechargerClient %p destructed", this);
}
//*****************************************************************************

MaCI::EMaCIError CRechargerClient::DoOpen(void)
{

  EMaCIError result = KMaCIError;
  
  // Checks.
  if(!IsActive()) {

    // Do Subs. using the MaCI provided function.
    result = SubscribeToInterface();

    // If all inits were fine...
    if (result == KMaCIOK) {
      // Start the Thread
      EnableSynchronousMessageReply();
      SetActive(true);
      CThread::RunThread();
      dPrint(4,"CRechargerClient::DoOpen() was succesfull.");
    }

  } else {
    dPrint(4,"RechargerClient already Active, not Opening again.");
    result = KMaCINotActive;

  }
  
  return result;
}
//*****************************************************************************

MaCI::EMaCIError CRechargerClient::DoClose(void)
{
  EMaCIError result = KMaCIError;
  
  if(IsActive()) {
    SetActive(false);

    // Wait for thread to complete.
    CThread::SetRequestTermination();
    /* CThread::CancelThread(); //Removed by script */
    CThread::WaitThread();
    result = UnsubscribeToInterface(TimeoutValue(2000));
  
    if(result == KMaCIOK){
      dPrint(4,"Succesfully closed RechargerClient");    
    }else{
      dPrint(4,"Unsubscribing failed!");
    }
    
    
  } else {
    dPrint(4, "RechargerClient not active, so not Closing.");
    result = KMaCINotActive;

  }
  
  return result;
}

//*****************************************************************************

bool CRechargerClient::GetStatusBySynchronousCall(unsigned int &aNumber,
                                                  unsigned int channel, 
                                                  unsigned int aTimeout_ms)
{
  bool result = false;
  CRechargerData rd;
  CRechargerData dd;
  dd.CreateInternalBinBag();

  // Only this func uses the sequence, so locking not required; BUT remember
  // correct locking scheme when this is not the case.
  ++iRechargerCommandSequence;
      
  // Set timestamp to current (default constructor of Common::TTimestamp)
  dd.SetTimestamp(Common::TTimestamp());
  
  // Add a recharger command
  dd.SetCommand(TCommand(KCommandQueryStatus));
  dd.SetChannel(TChannel(channel));
  // Send! ( Should probably check the Send() - but timeouted receive
  // gives the same )
  SendCommand(dd, iRechargerCommandSequence);

  // Now, get reply! (Give it 1000ms time to answer)
  GetCommandReply(rd, iRechargerCommandSequence, aTimeout_ms);

  // Extract data.
  const TStatus *de = rd.GetStatus();
  if (de) {
    aNumber = de->status;
    result = true;
  }

  return result;
}

//*****************************************************************************

bool CRechargerClient::GetVoltageBySynchronousCall(float &aNumber,
                                                  unsigned int channel, 
                                                  unsigned int aTimeout_ms)
{
  bool result = false;
  CRechargerData rd;
  CRechargerData dd;
  dd.CreateInternalBinBag();

  // Only this func uses the sequence, so locking not required; BUT remember
  // correct locking scheme when this is not the case.
  ++iRechargerCommandSequence;
      
  // Fill the frame and send
  dd.SetTimestamp(Common::TTimestamp());
  dd.SetCommand(TCommand(KCommandQueryVoltage));
  dd.SetChannel(TChannel(channel));
  SendCommand(dd, iRechargerCommandSequence);

  // Now, get reply! (Give it 1000ms time to answer)
  GetCommandReply(rd, iRechargerCommandSequence, aTimeout_ms);

  // Extract data.
  const TVoltage *de = rd.GetVoltage();
  if (de) {
    aNumber = de->voltage;
    result = true;
  }

  return result;
}


//*****************************************************************************

bool CRechargerClient::GetCurrentBySynchronousCall(float &aNumber,
                                                   unsigned int channel, 
                                                   unsigned int aTimeout_ms)
{
  bool result = false;
  CRechargerData rd;
  CRechargerData dd;
  dd.CreateInternalBinBag();

  // Only this func uses the sequence, so locking not required; BUT remember
  // correct locking scheme when this is not the case.
  ++iRechargerCommandSequence;
      
  // Fill the frame and send
  dd.SetTimestamp(Common::TTimestamp());
  dd.SetCommand(TCommand(KCommandQueryCurrent));
  dd.SetChannel(TChannel(channel));
  SendCommand(dd, iRechargerCommandSequence);

  // Now, get reply! (Give it 1000ms time to answer)
  GetCommandReply(rd, iRechargerCommandSequence, aTimeout_ms);

  // Extract data.
  const TCurrent *de = rd.GetCurrent();
  if (de) {
    aNumber = de->current;
    result = true;
  }

  return result;
}


//*****************************************************************************


bool CRechargerClient::GetChargeBySynchronousCall(float &aNumber,
                                                  unsigned int channel, 
                                                  unsigned int aTimeout_ms)
{
  bool result = false;
  CRechargerData rd;
  CRechargerData dd;
  dd.CreateInternalBinBag();

  // Only this func uses the sequence, so locking not required; BUT remember
  // correct locking scheme when this is not the case.
  ++iRechargerCommandSequence;
      
  // Fill the frame and send
  dd.SetTimestamp(Common::TTimestamp());
  dd.SetCommand(TCommand(KCommandQueryCharge));
  dd.SetChannel(TChannel(channel));
  SendCommand(dd, iRechargerCommandSequence);

  // Now, get reply! (Give it 1000ms time to answer)
  GetCommandReply(rd, iRechargerCommandSequence, aTimeout_ms);

  // Extract data.
  const TCharge *de = rd.GetCharge();
  if (de) {
    aNumber = de->charge;
    result = true;
  }

  return result;
}


//*****************************************************************************


bool CRechargerClient::GetRechargerEvent(CRechargerData &aData,
                                 unsigned int *aSeq,
                                 const unsigned int aTimeout_ms)
{  
  bool result = false;
  
  // Fallback in case the class is not active.
  if (!IsActive()) return false;

  Lock();
  
  if (aSeq == NULL) {
    // No sequence number defined. Just do direct copy of local data - no sync
    aData = iLastRechargerData;
    result = true;
    
  } else {
    
    if (iRechargerDataSequence <= *aSeq) {
      int time_left = aTimeout_ms;
      unsigned int time_begin = ownTime_get_ms();

      // The available scan is older than requested - must wait for time_left
      do {
        Wait(time_left, KEventRechargerData);
	time_left = aTimeout_ms - ownTime_get_ms_since(time_begin);
	
      } while(IsActive() && iRechargerDataSequence < *aSeq && time_left > 0);
      
      // Now, check whether the waiting resulted in the correct sequence
      if (iRechargerDataSequence > *aSeq) {
	// Yes :)
	aData = iLastRechargerData;
	*aSeq = iRechargerDataSequence;
	result = true;
        //dPrint(1,"Got data. *aSeq = %d, iRechargerDataSequence = %d", *aSeq, iRechargerDataSequence);
	
      } else {
	// No :(
	dPrint(5, "Failed to get RechargerData! (Timeout %dms)",
	       aTimeout_ms);
      }
      
    } else {
      // The available data is newer or matching.
      aData = iLastRechargerData;
      *aSeq = iRechargerDataSequence;
      //      dPrint(1,"Got data. *aSeq = %d, iRechargerDataSequence = %d", *aSeq, iRechargerDataSequence);
      result = true;
    }
  }
  
  Unlock();
  
  return result;
}
//*****************************************************************************
//*****************************************************************************
/**
 * This function is an _EXAMPLE_ of a directly receiving
 * function. When this function model is used, the Client class
 * doesn't have to implement a separate thread. (ProcessMessage and
 * ThreadFunction are not used). However, this means that no special
 * processing can be done by the interface hence this model is only
 * suitable for simple interfaces. This can ofcourse be later changed
 * without changing the public interface, so it's not a
 * architecturally significant decision. Use of this model is also
 * encouraged if possible, as it saves one extra thread thus saving a
 * (minimal) fraction of system resources.
 *
 * As this RechargerClient uses the more complex processing model as
 * example, this code block is disabled with precompiler directive,
 * but left here as on fully working example of receiving MaCI
 * dataelements directly from GIMI.
 */
#if 0
bool CRechargerClient::GetRechargerEvent(CRechargerData &aData,
                                 const unsigned int aTimeout_ms);
{
  EMaCIError result;
  gimi::GIMIMessage gmsg;
  
  if (IsActive()) {
    
    // Call the ReceiveMessage wrapper with 2s timeout
    result = ReceiveInterfaceMessage(gmsg, aTimeout_ms);
    
    // If result is OK, process the msg.
    if (result == KMaCIOK) {
      bool r;
      gim::binbag::CBinBag bb;
      CRechargerData d;
      
      // Decode BinBag.
      r = bb.Decode(gmsg.getData(), gmsg.getDatalength());
      if (r) {
        // BinBag OK. Decode RechargerData.
        r = d.DecodeFrom(&bb);
        if (r && d.GetRechargerEvent()) {
          // RechargerData ok. Copy to caller.
          aData.Copy(d);
          
        } else {
          result = KMaCIInvalidFormat;
          
        }
        
      } else {
        result = KMaCIInvalidFormat;
        
      }
    }
  } else {
    result = KMaCINotActive;

  }
  
  return (result == KMaCIOK);
}
#endif
//*****************************************************************************

bool CRechargerClient::GetCommandReply(CRechargerData &aData, const int aMessageID, 
                                   const int aTimeout_ms)
{ 
  EMaCIError result;
  gimi::GIMIMessage gmsg;
  
  // Call the ReceiveMessage wrapper with 2s timeout
  result = ReceiveSynchronousMessageReply(gmsg, aMessageID, aTimeout_ms);
  
  // If result is OK, process the msg.
  if (result == KMaCIOK) {
    bool r;
    gim::binbag::CBinBag bb;
    CRechargerData d;

    // Decode BinBag.
    r = bb.Decode(gmsg.getData(), gmsg.getDatalength());
    if (r) {
      // BinBag OK. Decode DummyData.
      r = d.DecodeFrom(&bb);
      if (r) {
        // RechargerData ok. Copy to caller.
        aData.Copy(d);

      } else {
        result = KMaCIInvalidFormat;

      }

    } else {
      result = KMaCIInvalidFormat;
      
    }
  }
  
  return (result == KMaCIOK);
}

//*****************************************************************************

bool CRechargerClient::SendCommand(const CRechargerData &aRechargerData, const int aMessageID)
{
  EMaCIError result = KMaCIError;
  
  if (IsActive()) {
    if (aRechargerData.GetCommand()) {
      // Foo.
      ++iRechargerCommandSequence; // Only this func. thread is updating this, so no locks required.
      
      // Send.
      SendInterfaceMessage(aRechargerData.GetBinBagContainerPtr()->GetBuffer(),
                           aRechargerData.GetBinBagContainerPtr()->GetBufferSize(),
                           iRechargerCommandSequence);
      
      dPrint(10,"SendInterfaceMessage called: %d:%d, seq: %d (%d bytes of payload sent)",
             iInterfaceMajor, iInterfaceMinor, 
             iRechargerCommandSequence-1,
             aRechargerData.GetBinBagContainerPtr()->GetBufferSize());
      // Result
      result = KMaCIOK;
      
    } else {
      dPrint(2,"No 'TCommand' element in provided CRechargerData object. Will not send!");
      result = KMaCIInvalidFormat;

    }
   
  } else {
    dPrint(2,"Unable to send RechargerData - Interface is not active! (Open() not called?)");
    result = KMaCINotActive;

  }


  return (result == KMaCIOK);
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

int CRechargerClient::ProcessMessage(const gimi::GIMIMessage &msg)
{
  int result = 0;
  gim::binbag::CBinBag bb;
  CRechargerData id;
  bool r;

  r = bb.Decode(msg.getData(), msg.getDatalength());
  if (r) {
    // Succesfully decoded as BinBag.
    r = id.DecodeFrom(&bb);
    if (r) {
      // Succesfully decoded as Recharger, now handle contents
      Lock();
      if (id.GetRechargerEvent()) {
        iLastRechargerData = id;
        ++iRechargerDataSequence;
        Notify(KEventRechargerData);
        dPrint(10,"Got RechargerData, Sequence now %u", iRechargerDataSequence);
      }
      Unlock();
      
      // Call the handler if set.
      if (iRechargerClientCallback) {
        dPrint(8,"Got Callback for RechargerDataEvent - executing!");
        iRechargerClientCallback->OnRechargerDataEvent(id,
                                               iRechargerDataSequence,
                                               *this);
        dPrint(8,"Callback for RechargerDataEvent - execution complete!");
      } 

    } else {
      dPrint(4,"WARNING: Received Recharger interface message, but failed to decode as RechargerData!");
      
    }
  }
  
  return result;
}

//*****************************************************************************

int CRechargerClient::ThreadFunction(const int aThreadNumber)
{
  int result = 0;
  const unsigned int hard_error_count_limit = 10;
  unsigned int hard_error_count = 0;
  EMaCIError e;
  gimi::GIMIMessage gmsg;
  
  assert(aThreadNumber == 0);
  assert(iGIMIPtr != NULL);
  
  dPrint(8, "GIMIMessage handler started");
  
  // Run as long as the thread should be active
  while(IsActive()) {
    // Call the ReceiveMessage wrapper with 1s timeout
    e = ReceiveInterfaceMessage(gmsg, 1000);
    if (e == KMaCIOK) {
      ProcessMessage(gmsg);

      // Reset error counter.
      if (hard_error_count) hard_error_count = 0;

    } else if (e != KMaCITimeout) {
      // Increment hard error count
      ++hard_error_count;
      
      // Check whether the hard error count limit is still under limit. 
      if (hard_error_count < hard_error_count_limit) {
        // Other error, try to recover by sleeping one second.
        dPrint(10,"ProcessMessage returned error %u, trying to recover by sleeping 1000ms (%u attempts left)",
               e, hard_error_count_limit-hard_error_count);
        ownSleep_ms(1000);

      } else {
        dPrint(3,"Error Recovery failed, RechargerClient ThreadFunction terminating...");

        // Break the while().
        break;
      }
      
    }
  }
  
  dPrint(8, "GIMIMessage handler stopped");
  SetActive(false);

  return result;
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
